package com.example.recyclerviewtest;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class AppAdapter extends RecyclerView.Adapter<AppAdapter.ViewHolder> {
    private List<AppItem> appItemList;

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        //加载RecyclerView子项的最外层布局
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.app_item_staggered_grid, parent, false);
        //创建ViewHolder实例，将上面获取到的view实例传入
        final ViewHolder holder = new ViewHolder(view);

        //为子项最外层布局设置点击事件
        holder.appItemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                AppItem appItem = appItemList.get(position);
                Toast.makeText(v.getContext(), "你点击了第" + (position + 1) + "个", Toast.LENGTH_SHORT).show();
            }
        });

        //为子项布局中的appName设置点击事件
        holder.appName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();  //获取当前适配器位置
                AppItem appItem = appItemList.get(position);  //从列表中获取相应的AppItem对象
                Toast.makeText(v.getContext(), "你点击了:" + appItem.getName() + "position:" + position, Toast.LENGTH_SHORT).show();
            }
        });

        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        //通过position参数获取子项位置，然后获取子项对象
        AppItem appItem = appItemList.get(position);
        //设置子项的图片和文字内容
        holder.appImage.setImageResource(appItem.getImageId());
        holder.appName.setText(appItem.getName());
    }

    @Override
    public int getItemCount() {
        return appItemList.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        View appItemView; //保存子项最外层布局，也即app_item布局
        ImageView appImage;
        TextView appName;

        public ViewHolder(View view) {
            //构造方法，传入子项最外层布局，绑定控件id
            super(view);
            appItemView = view;
            appImage = view.findViewById(R.id.app_img);
            appName = view.findViewById(R.id.app_name);
        }
    }

    public AppAdapter(List<AppItem> appItemList) {
        this.appItemList = appItemList;
    }
}
